<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 运单询价
 *
 * @icon fa fa-circle-o
 */
class Yundan extends Backend
{
    
    /**
     * Yundan模型对象
     * @var \app\admin\model\Yundan
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $dataLimit = true;
    protected $dataLimitField = 'chengyun_id';
    protected $noNeedRight = ["*"];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Yundan;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with("dingdan")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $key=>&$value)
            {
                $ddinfo=$value->dingdan;
              //  dump($ddinfo);die;
                $value['admin_id']=$ddinfo['weituofang'];
                $value['chepai']=get_chepai($value['chepai']);
                $value['admin_id']=get_fayun($value['admin_id']); //发运人
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function duizhanglist()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with("dingdan")
                ->where($where)
                ->where("duizhang_id", 0)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $key=>&$value)
            {
                $ddinfo=$value->dingdan;
                //  dump($ddinfo);die;
                $value['admin_id']=$ddinfo['weituofang'];
                $value['chepai']=get_chepai($value['chepai']);
                $value['admin_id']=get_fayun($value['admin_id']); //发运人
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();

    }


    public function feiyonglist($ids=null)
    {

        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $yundanid=$ids;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $m_feiyong=new \app\admin\model\Feiyong();
            $list = $m_feiyong
                ->where("yundan_id",$ids)
                ->where($where)
                ->order("id desc")
                ->paginate($limit);
            foreach ($list as $key=>&$value)
            {

            }
            $money= $m_feiyong
                ->where("yundan_id",$ids)
                ->where($where)->sum("feiyong");

            $result = array("total" => $list->total(), "rows" => $list->items(),"extend"=>["money"=>$money]);

            return json($result);
        }

        $this->assignconfig("yundanid",$yundanid);
        return $this->view->fetch();

    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {

                    $uid=$this->auth->id;
                    $dingdanid = $params['dingdan_id'];
                    $m_dingdan = new \app\admin\model\WlDingdan();
                    $dingdaninfo = $m_dingdan->where("id", $dingdanid)->find();
                    if (!$dingdaninfo) $this->error("订单错误");
                    $admin_id = $dingdaninfo['admin_id'];
                    $params['admin_id'] = $admin_id;
                    if (!isset($params['chepai'])) $this->error("请设置车辆");




                    $m_checi = new \app\admin\model\Checi();
                    $bianma = $m_checi->where("cheliang_id", $params['chepai'])
                        ->whereTime('addtime', 'today')
                        ->max("bianma");
                   // echo $m_checi->getLastSql();
                    $bianma++;

                   // echo ",$bianma,";
                    $bianmacode = date("Ymd") . str_pad($params['chepai'], 3, "0", STR_PAD_LEFT) .
                        str_pad($bianma, 3, "0", STR_PAD_LEFT);
//die($bianmacode);

                    $params['checi']=$bianma;


                    $result = $this->model->allowField(true)->save($params);
                    $yundan_id = $this->model->getLastInsID();


                    //设定车牌了,安排车次
                    $paicheinfo = [
                        'chengyun_id' => $uid,

                        'bianma' => $bianma,
                        'bianmacode' => $bianmacode,
                        'cheliang_id' => $params['chepai'],
                        'yundan_id' => $yundan_id,
                        'dingdan_id' => $dingdanid,
                        'admin_id' => $admin_id,
                        'addtime' => time(),
                    ];
                    $m_checi->allowField(true)->save($paicheinfo);





                    Db::commit();
                }
                catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $dingdanid=input("dingdanid/d",0);

        $m_dingdan=new \app\admin\model\WlDingdan();
        $dingdaninfo=$m_dingdan->where("id",$dingdanid)->find();

        $maxzhong=$dingdaninfo['zhongliang'];

        //已分配的重量
        $yfp=$this->model->where("dingdan_id",$dingdanid)->sum("zhongliang");
        $maxzhong=$maxzhong-$yfp;
        if($maxzhong<=0) $this->error("货物已经分配完毕!");


        $this->assign("maxzhong",$maxzhong);
        $this->assign("dingdanid",$dingdanid);
        $this->assign("dingdaninfo",$dingdaninfo);
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {

                    $oldchepai=$row['chepai'];

                    $result = $row->allowField(true)->save($params);
                    if($oldchepai!=$row['chepai'])
                    {
                        $m_checi=new \app\admin\model\Checi();
                        $bianma=$m_checi->where("cheliang_id",$params['chepai'])->max("bianma");
                        $bianma++;
                        //设定车牌了,安排车次
                        $paicheinfo=[
                            'bianma'=>$bianma,
                            'cheliang_id'=>$params['chepai'],
                            'yundan_id'=>$ids,
                            'dingdan_id'=>$params['dingdan_id'],
                            'addtime'=>time(),
                        ];
                        $m_checi->allowField(true)->save($paicheinfo);

                    }




                    Db::commit();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 派车
     */
    public function paiche($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 车辆列表
     */
    public function listche($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }


}
